package com.banciyuan.bcywebview.biz.main.mineinfo.mark;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.SpaceApi;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.biz.acgwork.MineAcgAdapter;
import com.banciyuan.bcywebview.biz.circles.discover.DiscoverCircleActivity;
import com.banciyuan.bcywebview.biz.circles.smooth.CircleSmoothActivity;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.AcgItem;

/**
 * Created by squall on 2016/1/21.
 */
public class OtherAcgFragment extends BaseLazyContainerFragment implements View.OnClickListener {
    protected View emptyView;
    protected ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;
    protected PullToRefreshListView refreshView;
    protected ListView mListView;
    private View footer;
    protected View footerView;

    private MineAcgAdapter mMineAcgAdapter;
    protected RequestQueue queue;

    private List<AcgItem> mAcgItemList = new ArrayList();

    protected boolean loading = false;
    protected int page = 1;
    protected boolean hasMore = true;

    protected String uid;
    protected int PAGE_LIMIT = 10;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View viewroot = inflater.inflate(R.layout.threecolumn_grid, null);
        initArgs();
        initProgressbar(viewroot);
        initUi(viewroot);
        initAction();
        return viewroot;
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initUi(View viewroot) {
        viewroot.findViewById(R.id.base_actionbar).setVisibility(View.GONE);
        refreshView = (PullToRefreshListView) viewroot.findViewById(R.id.pull_refresh_lv);
        mListView = refreshView.getRefreshableView();
        emptyView = viewroot.findViewById(R.id.layout_empty);
        emptyView.setVisibility(View.GONE);
        viewroot.findViewById(R.id.tv_go_order_acg).setOnClickListener(this);
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        footer = inflater.inflate(R.layout.maincircle_footer, mListView, false);
        TextView footerViewDesc = (TextView) footer.findViewById(R.id.footer_goacg);
        footerViewDesc.setText(getString(R.string.go_see_hot_work));
        footerViewDesc.setOnClickListener(this);
        footerView = footer.findViewById(R.id.rl_footer);
        footerView.setVisibility(View.GONE);
        mListView.addFooterView(footer);

        viewroot.findViewById(R.id.base_action_bar_home).setOnClickListener(this);

    }

    @Override
    protected void initData() {
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        if (!TextUtils.isEmpty(uid)) {
            paramsList.add(new BcyPair(HttpUtils.UID, uid));
        }
        paramsList.add(new BcyPair(HttpUtils.INDEX_P, String.valueOf(page)));
        paramsList.add(new BcyPair(HttpUtils.LIMIT, String.valueOf(PAGE_LIMIT)));
        final HashMap<String, String> params = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + SpaceApi.getFocusedcores();

        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, getActivity())) {
                    try {
                        JSONObject result = new JSONObject(s);
                        Gson gson = new Gson();
                        List<AcgItem> tempList = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<AcgItem>>() {
                        }.getType());
                        processEmptyView(tempList);
                        processFooterView(tempList);
                        processData(tempList);
                    } catch (Exception e) {
                        loading = false;
                        mProgressbarHelper.onFailed();
                        refreshView.onRefreshComplete();
                    }
                } else {
                    loading = false;
                    mProgressbarHelper.onFailed();
                    refreshView.onRefreshComplete();
                }
            }
        };

        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                loading = false;
                refreshView.onRefreshComplete();
                if (page == 1) {
                    mProgressbarHelper.onFailed();
                    emptyView.setVisibility(View.GONE);
                } else {
                    page -= 1;
                }
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(error, succ, url, getActivity(), params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, errorProxy);
        queue.add(stringRequest);
    }

    private void processFooterView(List<AcgItem> tempList) {
        if (tempList.size() < PAGE_LIMIT)
            footerView.setVisibility(View.VISIBLE);
    }

    private void processEmptyView(List<AcgItem> tempList) {
        if (tempList.size() == 0) {
            if (page == 1) {
                emptyView.setVisibility(View.VISIBLE);
            }
            hasMore = false;
        } else {
            emptyView.setVisibility(View.GONE);
        }
    }


    private void processData(List<AcgItem> templist) {
        loading = false;
        if (page == 1) {
            mAcgItemList.clear();
        }
        mAcgItemList.addAll(templist);
        if (null == mMineAcgAdapter) {
            mMineAcgAdapter = new MineAcgAdapter(getActivity(), mAcgItemList);
            mListView.setAdapter(mMineAcgAdapter);
        } else {
            mMineAcgAdapter.notifyDataSetChanged();
        }
        mProgressbarHelper.onSuccess();
        loading = false;
        refreshView.onRefreshComplete();
    }

    @Override
    protected void initArgs() {
        uid = getArguments().getString("uid", "");
        queue = VolleyQueue.getRquest(getActivity());
    }

    @Override
    protected void initProgressbar(View viewroot) {
        mProgressbarView = viewroot.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                hasMore = true;
                page = 1;
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initAction() {

        refreshView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (!loading) {
                    loading = true;
                    hasMore = true;
                    page = 1;
                    footerView.setVisibility(View.GONE);
                    initData();
                }
            }
        });

        refreshView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!loading) {
                    if (hasMore) {
                        loading = true;
                        page++;
                        initData();
                    }
                }
            }
        });

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                onItemClicked(i);
            }
        });
    }

    protected void onItemClicked(int i) {
        int postion = i - 1;
        if (postion < 0 || postion >= mAcgItemList.size()) return;

        Intent intent = new Intent();
        intent.putExtra(gotoUtil.INTENT_VALUE_ONE, mAcgItemList.get(postion).getReal_name());
        intent.putExtra(gotoUtil.INTENT_VALUE_TWO, mAcgItemList.get(postion).getId());
        intent.putExtra("from", 1);
        intent.setClass(getActivity(), CircleSmoothActivity.class);
        startActivity(intent);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.footer_goacg:
            case R.id.tv_go_order_acg:
                Intent intent = new Intent(getActivity(), DiscoverCircleActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, DiscoverCircleActivity.TYPE_WORK);
                startActivity(intent);
                break;
        }
    }

}
